package com.loiot.commons.wechat;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.loiot.commons.utils.JsonUtil;
import com.loiot.commons.utils.StringUtil;
import com.loiot.commons.wechat.dao.WechatLogDao;
import com.loiot.commons.wechat.pojo.WechatLog;

@Repository("saveWechatLog")
public class SaveWechatLog {
	private Logger log = LoggerFactory.getLogger(this.getClass());
	private int MAX_PARAMS = 10;
	@Autowired
	private WechatLogDao wechatLogDao;

	public boolean save(Map contentMap, String... args) {
		if (contentMap == null || contentMap.isEmpty()) {
			log.error("Map不能为空");
			return false;
		}
		if (args.length > MAX_PARAMS) {
			log.error("最大搜索参数各位为：" + MAX_PARAMS);
			return false;
		}
		WechatLog wechatLog = new WechatLog();
		try {
			fillWechatLog(wechatLog, contentMap, args);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		wechatLogDao.saveWechatLog(wechatLog);
		return true;
	}

	private void fillWechatLog(WechatLog wechatLog, Map contentMap,
			String[] args) throws Exception {
		// TODO Auto-generated method stub
		Class<?> wechatLogClass = Class
				.forName("com.loiot.commons.wechat.pojo.WechatLog");
		Field[] oFields = wechatLogClass.getFields();
		for (int j = 0; j < oFields.length; j++) {
			if (oFields[j].getName().startsWith("s")) {
				int sIndex = Integer
						.parseInt(oFields[j].getName().substring(1));
				if(sIndex>args.length)continue;
				String paraKey = args[sIndex-1];
				String paraVal = StringUtil.toString(contentMap.get(paraKey));
				oFields[j].set(wechatLog, paraVal);
			}
			if(oFields[j].getName().equals("content")){
				oFields[j].set(wechatLog, JsonUtil.toJson(contentMap));
			}

		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Class<?> wechatLogClass = null;
		try {
			wechatLogClass = Class
					.forName("com.loiot.commons.wechat.pojo.WechatLog");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		WechatLog wechatLog = new WechatLog();
		Field[] oFields = wechatLogClass.getFields();
		for (int j = 0; j < oFields.length; j++) {
			if (oFields[j].getName().startsWith("s")) {
				int sIndex = Integer
						.parseInt(oFields[j].getName().substring(1));
				try {
					oFields[j].set(wechatLog, j * 10 + "");
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		try {
			System.out.println("the json: " + JsonUtil.toJson(wechatLog));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
